import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../common/utils/system_ui_utils.dart';
import 'index.dart';

class FundsPage extends GetView<FundsController> {
  const FundsPage({super.key});

  @override
  Widget build(BuildContext context) {
    // ✅ 设置透明状态栏 - 浅色图标（适配深红色背景）
    SystemUIUtils.setTransparentStatusBarLight();
    
    return Scaffold(
      backgroundColor: Colors.white,
      extendBodyBehindAppBar: true,  // ✅ 让body延伸到AppBar下方
      appBar: AppBar(
        backgroundColor: Colors.transparent,  // ✅ 透明背景
        foregroundColor: Colors.white,        // ✅ 白色文字/图标
        elevation: 0,                         // ✅ 无阴影
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Get.back(),
        ),
        title: const Text(
          '积分充值',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        centerTitle: true,
      ),
      body: GetBuilder<FundsController>(
        init: FundsController(),
        id: "funds",
        builder: (_) {
          if (controller.isLoading.value) {
            return const Center(child: CircularProgressIndicator());
          }
          
          return Column(
            children: [
              // 顶部固定区域
              Column(
                children: [
                  // 顶部积分信息卡片
                  _buildPointsHeader(),
                  
                  // 积分加油站
                  _buildPointsPackages(),
                  
                  // 积分变更历史标题
                  _buildHistoryTitle(),
                ],
              ),
              
              // 可滚动的历史记录列表
              Expanded(
                child: _buildHistoryListView(),
              ),
            ],
          );
        },
      ),
      bottomNavigationBar: _buildBottomButton(),
    );
  }

  // 顶部积分信息卡片
  Widget _buildPointsHeader() {
    // ✅ 获取状态栏高度
    final statusBarHeight = MediaQuery.of(Get.context!).padding.top;
    const appBarHeight = 56.0;  // AppBar标准高度
    
    return Container(
      decoration: const BoxDecoration(
        color: Color(0xFFD85D6D), // 统一的深红色
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(16),
          bottomRight: Radius.circular(16),
        ),
      ),
      // ✅ 动态计算顶部padding：状态栏 + AppBar + 自定义间距
      padding: EdgeInsets.fromLTRB(
        16, 
        statusBarHeight + appBarHeight + 8,  // 顶部动态计算
        16, 
        12
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              // 金币图标
              Container(
                width: 50,
                height: 50,
                decoration: BoxDecoration(
                  color: const Color(0xFFD4915F),
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 6,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: const Center(
                  child: Text(
                    '\$',
                    style: TextStyle(
                      fontSize: 26,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFFF4D03F),
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 12),
              // 积分和等级信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '${controller.userPoints}积分',
                      style: const TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                    const SizedBox(height: 3),
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 2,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.3),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Text(
                            controller.levelDisplayText,
                            style: const TextStyle(
                              fontSize: 14,
                              color: Colors.white,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                        const Spacer(),
                        Text(
                          '升级所需积分 ${controller.pointsToNextLevel}',
                          style: const TextStyle(
                            fontSize: 13,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          // 进度条
          ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: LinearProgressIndicator(
              value: controller.levelProgressPercent,
              minHeight: 6,
              backgroundColor: Colors.white.withOpacity(0.3),
              valueColor: const AlwaysStoppedAnimation<Color>(Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  // 积分套餐列表（横向滚动）
  Widget _buildPointsPackages() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 16),
            child: Text(
              '积分加油站',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
          ),
          const SizedBox(height: 10),
          // 横向滚动套餐列表
          Obx(() {
            if (controller.pointsPackages.isEmpty) {
              return const Center(
                child: Padding(
                  padding: EdgeInsets.all(20),
                  child: Text('暂无套餐'),
                ),
              );
            }
            
            return SizedBox(
              height: 115,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                padding: const EdgeInsets.symmetric(horizontal: 16),
                itemCount: controller.pointsPackages.length,
                itemBuilder: (context, index) {
                  final package = controller.pointsPackages[index];
                  final isSelected = controller.selectedPackage.value?.id == package.id;
                  return Padding(
                    padding: EdgeInsets.only(
                      right: index < controller.pointsPackages.length - 1 ? 10 : 0,
                    ),
                    child: _buildPackageCard(package, isSelected: isSelected),
                  );
                },
              ),
            );
          }),
        ],
      ),
    );
  }

  // 单个套餐卡片
  Widget _buildPackageCard(package, {bool isSelected = false}) {
    return GestureDetector(
      onTap: () => controller.selectPackage(package),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        width: 120,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
          border: Border.all(
            color: isSelected ? const Color(0xFFE85D5D) : Colors.grey[300]!,
            width: isSelected ? 2.5 : 1,
          ),
          boxShadow: [
            BoxShadow(
              color: isSelected
                  ? const Color(0xFFE85D5D).withOpacity(0.25)
                  : Colors.black.withOpacity(0.04),
              blurRadius: isSelected ? 8 : 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Stack(
          children: [
            // 热门标签
            if (package.isHot)
              Positioned(
                top: 0,
                right: 0,
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 10,
                    vertical: 3,
                  ),
                  decoration: const BoxDecoration(
                    color: Color(0xFFE85D5D),
                    borderRadius: BorderRadius.only(
                      topRight: Radius.circular(8),
                      bottomLeft: Radius.circular(8),
                    ),
                  ),
                  child: const Text(
                    '热门',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 10,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            // 选中状态标识
            if (isSelected)
              Positioned(
                top: 6,
                left: 6,
                child: Container(
                  width: 20,
                  height: 20,
                  decoration: const BoxDecoration(
                    color: Color(0xFFE85D5D),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(
                    Icons.check,
                    color: Colors.white,
                    size: 14,
                  ),
                ),
              ),
            // 内容
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '${package.points}积分',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: isSelected ? const Color(0xFFE85D5D) : Colors.black87,
                    ),
                  ),
                  const SizedBox(height: 6),
                  Text(
                    '¥${package.price.toStringAsFixed(0)}',
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFFE85D5D),
                    ),
                  ),
                  const SizedBox(height: 3),
                  Text(
                    package.name,
                    style: TextStyle(
                      fontSize: 10,
                      color: Colors.grey[600],
                    ),
                    textAlign: TextAlign.center,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 历史记录标题
  Widget _buildHistoryTitle() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 6, 16, 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          const Text(
            '积分变更历史',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
            ),
          ),
          Text(
            '共${controller.pointsHistory.length}条',
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  // 历史记录列表视图
  Widget _buildHistoryListView() {
    return Obx(() {
      if (controller.pointsHistory.isEmpty) {
        return const Center(
          child: Text(
            '暂无记录',
            style: TextStyle(
              color: Colors.grey,
              fontSize: 14,
            ),
          ),
        );
      }
      
      return ListView.builder(
        padding: const EdgeInsets.only(bottom: 80),
        itemCount: controller.pointsHistory.length,
        itemBuilder: (context, index) {
          final item = controller.pointsHistory[index];
          return _buildHistoryItem(item);
        },
      );
    });
  }

  // 单条历史记录
  Widget _buildHistoryItem(item) {
    return Dismissible(
      key: Key('history_${item.id}_${item.changeTime}'),
      background: Container(
        color: Colors.red,
        alignment: Alignment.centerRight,
        padding: const EdgeInsets.only(right: 20),
        child: const Text(
          '系统消耗',
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      direction: DismissDirection.endToStart,
      confirmDismiss: (direction) async {
        // 可以在这里添加确认对话框
        return false; // 暂时禁用删除
      },
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.grey[50],
          borderRadius: BorderRadius.circular(10),
          border: Border.all(color: Colors.grey[200]!),
        ),
        child: Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    item.changeTime,
                    style: TextStyle(
                      fontSize: 11,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    item.reason,
                    style: const TextStyle(
                      fontSize: 14,
                      color: Colors.black87,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
            const SizedBox(width: 12),
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text(
                  item.formattedChangeAmount,
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: item.isIncrease 
                        ? const Color(0xFF4CAF50) 
                        : const Color(0xFFE85D5D),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 底部按钮
  Widget _buildBottomButton() {
    return Obx(() {
      final hasSelected = controller.selectedPackage.value != null;
      final selectedPackage = controller.selectedPackage.value;
      
      return Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 10,
              offset: const Offset(0, -2),
            ),
          ],
        ),
        child: SafeArea(
          child: SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: hasSelected ? controller.goToPayment : null,
              style: ElevatedButton.styleFrom(
                backgroundColor: hasSelected
                    ? const Color(0xFFE85D5D)
                    : const Color(0xFFE0E0E0),
                foregroundColor: hasSelected
                    ? Colors.white
                    : const Color(0xFF9E9E9E),
                padding: const EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                // elevation: hasSelected ? 2 : 0,
              ),
              child: Text(
                hasSelected
                    ? '立即支付 ¥${selectedPackage!.price.toStringAsFixed(2)}'
                    : '请选择积分套餐',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ),
      );
    });
  }
}
